import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render
# Create your views here.
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from roomManage import models
from roomManage.seriallizers import RoomTypeSeriallizer, RoomFloorSeriallizer, RoomMasterSeriallizer, RoomsSeriallizer
from tools.authToken import create_token, userAuth, userCateAuth
from tools.encryption import getSha256
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_file_type, get_time_uid, get_uuid, delete_file

imgType_list = ['.png', '.jpg']

# 房间类型
class RoomType(APIView):

    # @method_decorator([userAuth, userCateAuth])
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            all = get_json_values("all", body)
            if all:
                floors = models.RoomType.objects.filter().order_by("sort")
                for fl in floors:
                    li.append({
                        "id": fl.id,
                        "name": fl.name,
                    })
                resp = {"code": 1, "data": li}
                # resp = json.dumps(resp)
                return Response(resp)

            roomtypes = models.RoomType.objects.filter().order_by("sort")

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = RoomTypeSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total':total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.RoomType.objects.create(
                name=name,
                sort=sort,
                describe=describe
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.RoomType.objects.filter(id=id).update(
                name=name,
                sort=sort,
                describe=describe
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            clothing = models.RoomType.objects.filter(id__in=id_list)
            clothing.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

# 房间楼层
class RoomFloor(APIView):

    @method_decorator([userAuth, userCateAuth])
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()

            all = get_json_values("all", body)

            if all:
                floors = models.RoomFloor.objects.filter().order_by("sort")
                for fl in floors:
                    li.append({
                        "id": fl.id,
                        "name": fl.name,
                    })
                resp = {"code": 1, "data": li}
                # resp = json.dumps(resp)
                return Response(resp)
            roomtypes = models.RoomFloor.objects.filter().order_by('id')
            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count
            seriallizer = RoomFloorSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total':total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.RoomFloor.objects.create(
                name=name,
                sort=sort,
                describe=describe
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            describe = get_json_values("describe", body, None)

            if models.RoomFloor.objects.filter(id=id).update(
                name=name,
                sort=sort,
                describe=describe
            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            clothing = models.RoomFloor.objects.filter(id__in=id_list)
            clothing.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)


# 房间
class RoomMaster(APIView):
    @method_decorator([userAuth, userCateAuth])
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            all = get_json_values('all', body)
            if all:
                roomtypes = models.RoomMaster.objects.filter().order_by("sort")
                seriallizer = RoomMasterSeriallizer(roomtypes, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)

            roomtypes = models.RoomMaster.objects.filter().order_by("sort")
            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(roomtypes, page_size)
            roomtypes = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = RoomMasterSeriallizer(roomtypes, many=True)
            resp = {"code": 1, "data": seriallizer.data, "total": total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            # body = json.loads(request.body)
            body = request.POST.dict()

            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            type_id = get_json_values("type_id", body, None)
            floor_id = get_json_values("floor_id", body, None)
            # status = get_json_values("status", body, 0)

            file = request.FILES.get("img", None)

            filepath = None
            # icon_type = ''
            # file_name = ''
            if file:
                file_nem, file_type = get_file_type(str(file))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'room', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/room/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)

            if models.RoomMaster.objects.create(
                name=name,
                sort=sort,
                uuid=get_uuid(),
                type_id=type_id,
                floor_id=floor_id,
                imgPath=filepath,
            ):

                resp = {"code": 1, "data": li, "msg": '新建成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            # body = json.loads(request.body)
            body = request.POST.dict()
            id = get_json_values("id", body)
            name = get_json_values("name", body)
            sort = get_json_values("sort", body, 0)
            type_id = get_json_values("type_id", body, None)
            floor_id = get_json_values("floor_id", body, None)
            # status = get_json_values("status", body, 0)

            file = request.FILES.get("img", None)
            filepath = None
            # icon_type = ''
            # file_name = ''
            item = models.RoomMaster.objects.filter(id=id)
            if file:
                file_nem, file_type = get_file_type(str(file))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'room', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/room/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)

                item.update(
                    imgPath=filepath
                )
            if item.update(
                name=name,
                sort=sort,
                type_id=type_id,
                floor_id=floor_id,

            ):
                resp = {"code": 1, "data": li, "msg": '修改成功'}
            else:
                resp = {"code": 0, "data": li, "msg": '修改失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator([userAuth, userCateAuth])
    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            id_list = get_json_values("id", body)
            # print(id_list)
            roommaster = models.RoomMaster.objects.filter(id__in=id_list)
            for rm in roommaster:
                if rm.imgPath:
                    delete_file(settings.BASE_DIR+rm.imgPath)
            roommaster.delete()

            resp = {"code": 1, "data": li,"msg": "删除成功"}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

# 首页获取数据
class GetRooms(APIView):


    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            roomId = get_json_values('roomId', body)
            # print(kwargs['userinfo'])
            search_dict = {}
            if roomId:
                search_dict['id'] = roomId
            rooms = models.RoomMaster.objects.filter(**search_dict).order_by("sort")

            roomtotal = rooms.count()
            roomable = rooms.filter(status=1).count()
            roomunable = roomtotal-roomable

            count = {
                'roomtotal': roomtotal,
                'roomable': roomable,
                'roomunable': roomunable
            }

            # rooms = rooms.filter(status=1)

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)
            paginator = Paginator(rooms, page_size)
            rooms = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = RoomsSeriallizer(rooms, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'count': count,"total": total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        # print(resp)
        return Response(resp)
